package com.aaa.sso.service;

import com.aaa.entity.Admin;
import com.aaa.entity.Permission;
import com.aaa.sso.feign.AdminFeign;
import com.aaa.sso.feign.PermissionFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: qy158-cai-parent
 * @description:
 * @author: 闫克起2
 * @create: 2023-02-22 16:10
 **/
@Service
public class UserService implements UserDetailsService {
    @Autowired
    private AdminFeign adminFeign;
    @Autowired
    private PermissionFeign permissionFeign;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据用户名查询用户信息
        Admin admin = adminFeign.getByName(username);
        if(admin!=null){
            //2.根据当前用户查询该用户具有的权限。
            List<Permission> permissions = permissionFeign.getPermissionByUserid(admin.getId());
            Collection<SimpleGrantedAuthority> authorities = permissions.stream().filter(item->item.getPermissionValue()!=null).filter(item->item.getType()==2).map(item->new SimpleGrantedAuthority(item.getPermissionValue())).collect(Collectors.toList());
            User user = new User(admin.getAdminUsername(),admin.getAdminPassword(),authorities);
            return user;
        }
        return null;
    }
}






















